package video_service

import (
	"fmt"
	ffmpeg "github.com/u2takey/ffmpeg-go"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
	"strings"
)

var (
	outputDir = "D:\\ShanghaiLixiang\\audio"
)

func InFormat1(target string, str_array []string) bool {
	for _, element := range str_array {
		if target == element {
			return true
		}
	}
	return false
}

// 提取MP3
func ExtractMp3(inputVideoPath string) string {
	_formatArr := []string{"mp4", "flv"}
	_, _file := filepath.Split(inputVideoPath)
	_tmps := strings.Split(_file, ".")
	_ext := _tmps[len(_tmps)-1]
	if !InFormat1(_ext, _formatArr) {
		fmt.Println("格式不支持")
	}

	baseName := strings.TrimSuffix(_file, filepath.Ext(_file))
	_resultVideoPath := filepath.Join(outputDir, fmt.Sprintf("%s.%s", baseName, "mp3"))

	err := ffmpeg.Input(inputVideoPath).
		Output(_resultVideoPath, ffmpeg.KwArgs{"acodec": "libmp3lame"}).
		OverWriteOutput().ErrorToStdOut().Run()
	if err != nil {
		fmt.Println(err)
	}
	return _resultVideoPath
}

func Mp4ToMp3(fileHeader *multipart.FileHeader) (string, error) {
	// 验证文件格式
	_formatArr := []string{"mp4", "flv"}
	filename := fileHeader.Filename
	_ext := filepath.Ext(filename)
	if !InFormat1(strings.TrimPrefix(_ext, "."), _formatArr) {
		return "", fmt.Errorf("unsupported format: %s", _ext)
	}

	// 创建临时目录
	tempDir := filepath.Join(os.TempDir(), "video_processing")
	if err := os.MkdirAll(tempDir, 0755); err != nil {
		return "", fmt.Errorf("failed to create temp dir: %v", err)
	}

	// 保存上传文件到临时目录
	srcFile, err := fileHeader.Open()
	if err != nil {
		return "", fmt.Errorf("failed to open uploaded file: %v", err)
	}
	defer srcFile.Close()

	tempInputPath := filepath.Join(tempDir, filename)
	dstFile, err := os.Create(tempInputPath)
	if err != nil {
		return "", fmt.Errorf("failed to create temp file: %v", err)
	}
	defer dstFile.Close()

	if _, err = io.Copy(dstFile, srcFile); err != nil {
		return "", fmt.Errorf("failed to save uploaded file: %v", err)
	}

	// 生成输出路径
	baseName := strings.TrimSuffix(filename, _ext)
	outputPath := filepath.Join(outputDir, fmt.Sprintf("%s.mp3", baseName))

	// 执行转码
	err = ffmpeg.Input(tempInputPath).
		Output(outputPath, ffmpeg.KwArgs{"acodec": "libmp3lame"}).
		OverWriteOutput().
		ErrorToStdOut().
		Run()

	// 清理临时文件
	os.Remove(tempInputPath)

	if err != nil {
		return "", fmt.Errorf("ffmpeg conversion failed: %v", err)
	}

	return outputPath, nil
}
